﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test1
{
    //static 修饰的成员，不需要实例化对象即可使用
    //无static修饰的成员，则需要通过实例化对象才能使用


    class DBhelper
    {
        private readonly string sqlCommandString="SELECT *FROM userInfo";

        private readonly string connectionString = "server=.;database=test;uid=sa;pwd=123456";

        public static void  PrintUserInfo()//访问 修饰符
        {
            //连接数据库
            string connectionString = "server=.;database=test;uid=sa;pwd=123456";

            //声明对象
            SqlConnection sqlConnection = new SqlConnection(connectionString);

            //打开连接
            sqlConnection.Open();

            //获取表数据第一种
            var sqlCommandString = "SELECT *FROM userInfo";
            SqlCommand sqlCommand = new SqlCommand(sqlCommandString, sqlConnection);
            //只读，数据不多
            var Sdr = sqlCommand.ExecuteReader();

            Console.WriteLine("{0}\t{1}\t{2}\t", "Id", "用户名", "性别");
            while (Sdr.Read())
            {
                Console.WriteLine("{0}\t{1}\t{2}\t", Sdr["userId"], Sdr["username"], Sdr["usersex"]);
            }

            //关闭连接
            sqlConnection.Close();
        }
        public  void PrintUserInfoAD()
        {
            //获取表数据第二种，大部分使用
            //可以更新表数据

            SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommandString, connectionString);

            DataTable dataTable = new DataTable();
            dataAdapter.Fill(dataTable);

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("{0}\t{1}\t{2}\t", "Id", "用户名", "性别");
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                Console.WriteLine("{0}\t{1}\t{2}\t", dataTable.Rows[i]["userId"], dataTable.Rows[i]["username"], dataTable.Rows[i]["usersex"]);
            }
            
        }
    }
}
